package com.zongzi.stock.module;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;

/**
 * ItemDragHelperCallback
 * Created by YoKeyword on 15/12/29.
 */
public class ItemDragHelperCallback extends ItemTouchHelper.Callback {

    //自定义监听事件
    public static interface OnItemDragListener {

        void onSwipe(int position);
    }

    private OnItemDragListener mOnItemDragListener = null;

    public void setOnItemDragListener(OnItemDragListener listener) {
        mOnItemDragListener = listener;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags;
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager || manager instanceof StaggeredGridLayoutManager) {
            dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        } else {
            dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        }
        // 如果想支持滑动(删除)操作, swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END
        // 不支持滑动操作 swipeFlags = 0;
        // 仅支持向左滑动
        int swipeFlags = ItemTouchHelper.START;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        if (recyclerView.getAdapter() instanceof StockListAdapter) {
            StockListAdapter mStockListAdapter = ((StockListAdapter) recyclerView.getAdapter());
            mStockListAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        }
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        if (mOnItemDragListener != null) {
            mOnItemDragListener.onSwipe(viewHolder.getAdapterPosition());
        }
    }


    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        // 不在闲置状态
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if (recyclerView.getAdapter() instanceof StockListAdapter) {
            StockListAdapter mStockListAdapter = ((StockListAdapter) recyclerView.getAdapter());
            mStockListAdapter.setItemBgNor(viewHolder);
        }
        super.clearView(recyclerView, viewHolder);
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        // 不需要滑动功能
        return true;
    }
}